﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Automation.BDaq;

namespace CrankShaftAnalysisSystem.Devices
{
    public class SnapCounter
    {
        public UdCounterCtrl udControl { get; set; }
        public EventId SnapEventId { get; private set; }
        public bool RefIndexFound { get; private set; } = false;
        public string ConfigFile { get; set; }
        public SnapCounter(string file_path)
        {
            udControl = new UdCounterCtrl();
            try
            {
                udControl.SelectedDevice = new DeviceInformation("PCI-1784,BID#0");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Init PCI Card Error: {ex.Message}");
            }
            udControl.UdCntrEvent += UdCntrEvent;
            ConfigFile = file_path;
        }

        private void UdCntrEvent(object sender, UdCntrEventArgs e)
        {
            int length = ((UdCounterCtrl)sender).Features.UdSnapEventSources.Length;
            for (int srcLen = 0; srcLen < length; ++srcLen)
            {
                if (SnapEventId == e.Id)
                {
                    RefIndexFound = true;
                    break;
                }
            }
        }

        public void Begin()
        {
            RefIndexFound = false;
            var ret = udControl.LoadProfile(ConfigFile);
            if (ret != ErrorCode.Success)
                Console.WriteLine($"Load Config File Failed : {ret}");
            if (udControl.Channels is null)
                return;
            udControl.Channels[0].CountingType = CountingType.AbPhaseX4;
            udControl.Channels[0].ResetTimesByIndex = -1;
            udControl.ChannelStart = 0;
            udControl.ChannelCount = 1;
            var snapSource = udControl.Features.UdSnapEventSources;
            SnapEventId = snapSource[0];
            udControl.SnapStart(snapSource[0]);
            udControl.Enabled = true;
        }

        public int GetValue()
        {
            int ret;
            var err = udControl.Read(out ret);
            if (err != ErrorCode.Success)
                throw new Exception("Read Counter Failed.");
            return ret;
        }
    }
}
